package com.deyang.ui.basepermissionui;

import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;


import com.deyang.callback.RequestPermissionsCallBack;
import com.deyang.util.PermissionUtil;

import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class BasePermissionActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {


    private RequestPermissionsCallBack permissionsCallBack;
    //永久拒绝权限提示
    private String permanentlyDeniedPerMsg = "";

    /**
     * 申请权限
     *
     * @param activity
     * @param rationale   申请前提示
     * @param requestCode 申请码
     * @param permissions 申请权限
     */
    public void requestPermissions(Activity activity, String rationale, String permanentlyDeniedPerMsg
            , int requestCode, RequestPermissionsCallBack callBack, String... permissions) {
        this.permissionsCallBack = callBack;
        this.permanentlyDeniedPerMsg = permanentlyDeniedPerMsg;
        PermissionUtil.requestPermissions(activity, rationale, requestCode, permissions);
    }

    /**
     * 重写onRequestPermissionsResult，用于接受请求结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //将请求结果传递EasyPermission库处理
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 权限申请通过
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        permissionsCallBack.onPermissionsGranted(perms);
    }

    /**
     * 权限申请拒绝
     *
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        /**
         * 永久拒绝
         * 若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不在提示'，且拒绝权限。
         * 这时候，需要跳转到设置界面去，让用户手动开启。      拒绝 false        取消 false        不在询问true
         */
        boolean isPermanentlyDenied = EasyPermissions.somePermissionPermanentlyDenied(this, perms);
        if (isPermanentlyDenied) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("开启权限")
                    .setRationale("因您拒绝了" + permanentlyDeniedPerMsg + "权限导致此功能无法使用，是否进入设置开启权限")
                    .build()
                    .show();
        }
    }
}
